import { adoptsSubmit, getCuesSubmitPage, scoresSubmit } from '@/services/api/api-cues-submit';
import { CheckCircleOutlined, FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import ProCard from '@ant-design/pro-card';
import { ModalForm, ProFormDigit } from '@ant-design/pro-form';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { Space, Table, Tag, Typography, message } from 'antd';
import moment from 'moment';
import React, { useRef } from 'react';
import { useAccess } from 'umi';
import AddSubmit from './AddSubmit';
import DetailsSubmit from './DetailsSubmit';
import { findTagColor } from '@/utils/findTagColor';

interface TableTopicPlanProps {
  run: number;
  plan: CuesTopicData.TopicPlan;
  length: number
}

const TableTopicPlan: React.FC<TableTopicPlanProps> = (props) => {
  const { run, plan, length } = props;
  const access = useAccess();
  const ref = useRef<ActionType>();

  return (
    <ProCard
      title={
        <span
          style={{
            fontSize: 18,
            fontWeight: 'bold',
          }}
        >
          {length >= 2 || access.线索上报x选题计划x计划列表x创建计划x多条选题计划 ? plan?.name : ""}
        </span>
      }
      style={{ marginTop: '24px' }}
    // extra={
    //   access.线索上报x选题计划x选题列表x上报线索 &&
    //   run === 1 && (
    //     <AddSubmit
    //       key="add_submit"
    //       topicPlan={plan}
    //       onRefurbish={() => {
    //         ref?.current?.reload();
    //       }}
    //     />
    //   )
    // }
    >
      {(plan?.describes && access.线索上报x选题计划x计划列表x创建计划x多条选题计划) && (
        <Typography.Paragraph>
          <pre
            style={{
              whiteSpace: 'pre-wrap',
            }}
          >
            {plan?.describes}
          </pre>
        </Typography.Paragraph>
      )}
      <ProTable<CuesSubmitData.SubmitPage>
        columns={[
          {
            title: '上报线索',
            dataIndex: 'articleName',
            // copyable: true,
            ellipsis: true,
            width: '200px',
            align: 'center',
            key: 'articleName',
            render: (dom, record, _index, action) => {
              return (
                <div
                  style={{
                    textAlign: 'left',
                    textOverflow: 'ellipsis',
                    whiteSpace: "nowrap",
                    overflow: 'hidden'
                  }}
                >
                  {record.isImage === 1 ? <FileImageOutlined /> : <></>}
                  {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
                  {access.线索上报x选题计划x选题列表x详情页面 ? (
                    <DetailsSubmit
                      table='topic'
                      id={record.id}
                      name={record.articleName}
                      onRefurbish={() => {
                        action?.reload();
                      }}
                    />
                  ) : (
                    <a
                      onClick={() => {
                        message.error('无访问权限');
                      }}
                    >
                      {record.articleName}
                    </a>
                  )}
                </div>
              );
            },
          },
          {
            title: '行业',
            dataIndex: 'articleIndustryName',
            key: 'articleIndustryName',
            width: '80px',
            align: 'center',
            search: false,
          },
          {
            title: '单位',
            key: 'articleOrganizationTopName',
            dataIndex: 'articleOrganizationTopName',
            width: '180px',
            search: false,
            align: 'center',
            render: (_, row) => (
              <>
                <Tag color={findTagColor(row.articleOrganizationTopName)}>{row.articleOrganizationTopName}</Tag>
                {row.articleOrganizationName}
              </>
            ),
          },
          {
            title: '新闻联络人',
            dataIndex: 'articleAccountName',
            // copyable: true,
            ellipsis: true,
            search: false,
            width: '100px',
            align: 'center',
            key: 'articleAccountName',
          },
          {
            title: '上报日期',
            dataIndex: 'createdTimes',
            key: 'createdTimes',
            valueType: 'dateRange',
            hideInTable: true,
            fieldProps: {
              allowClear: true,
              placeholder: ['开始日期', '结束日期'],
              format: 'YYYY-MM-DD',
              ranges: {
                今日: [moment(), moment()],
                本月: [moment().startOf('month'), moment().endOf('month')],
                上月: [
                  moment().startOf('month').subtract(1, 'months'),
                  moment().endOf('month').subtract(1, 'months'),
                ],
                最近7天: [moment().subtract(6, 'days'), moment()],
                最近60天: [moment().subtract(59, 'days'), moment()],
                最近90天: [moment().subtract(89, 'days'), moment()],
              },
            },
          },
          {
            title: '创建时间',
            dataIndex: 'createdTime',
            key: 'createdTime',
            width: '120px',
            align: 'center',
            search: false,
          },

          {
            title: '是否录用',
            dataIndex: 'isAdopt',
            key: 'isAdopt',
            valueType: 'select',
            width: '80px',
            align: 'center',
            fixed: 'right',
            hideInTable: !access.线索上报x选题计划x选题列表x收录线索,
            hideInSearch: !access.线索上报x选题计划x选题列表x收录线索,
            valueEnum: {
              0: { text: '未录用' },
              1: { text: '已录用' },
            },
            render: (_, record) => (
              <Space>
                <Tag color={record.isAdopt === 0 ? '#F9CF59' : '#1AA15F'} key="isAdopt">
                  {record.isAdopt === 0 ? '未录用' : '已录用'}
                </Tag>
              </Space>
            ),
          },
          {
            title: '评分',
            dataIndex: 'score',
            key: 'score',
            width: '50px',
            align: 'center',
            fixed: 'right',
            search: false,
            hideInTable: !access.线索上报x选题计划x选题列表x评分线索,
            hideInSearch: !access.线索上报x选题计划x选题列表x评分线索,
          },
          // {
          //   title: '刊播情况',
          //   dataIndex: 'isPublish',
          //   key: 'isPublish',
          //   valueType: 'select',
          //   width: '80px',
          //   align: 'center',
          //   // hideInSearch: access.选题报送x配置x分类x媒体,
          //   // hideInTable: access.选题报送x配置x分类x媒体,
          //   valueEnum: {
          //     0: { text: '未刊播' },
          //     1: { text: '已刊播' },
          //   },
          //   render: (_, record) => (
          //     <Space>
          //       <Tag color={record.isPublish === 0 ? '#CCCCCC' : '#1AA15F'} key="isPublish">
          //         {record.isPublish === 0 ? '查看' : '查看'}
          //       </Tag>
          //     </Space>
          //   ),
          // },
        ]}
        // actionRef={actionRef}
        request={async (params = {}) => {
          // if (params.organizationIds) {
          //   const organizationParentIds: string[] = [];
          //   let organizationIds: string[] = [];

          //   params.organizationIds.forEach((item: string | any[]) => {
          //     if (item.length === 1) {
          //       organizationParentIds.push(item[0]);
          //     } else if (item.length > 1) {
          //       organizationIds.push(item[1]);
          //     }
          //   });
          //   organizationParentIds.forEach((id) => {
          //     const ids = articleOrganizations.find((item) => item.id === id).children;
          //     organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
          //   });
          //   params.articleOrganizationIds = organizationIds;
          // }
          const response = await getCuesSubmitPage({
            ...params,
            topicId: plan?.topicId,
            topicPlanId: plan?.id,
          });

          return Promise.resolve({
            data: response.data.data,
            total: response.data.total,
            success: response.code === 0,
          });
        }}
        actionRef={ref}
        ghost
        rowKey="id"
        dateFormatter="string"
        bordered
        search={{
          filterType: 'light',
        }}
        // search={false}
        sticky
        scroll={{
          x: '1300px',
        }}
        cardProps={{
          style: {
            padding: 0,
          },
        }}
        toolbar={{
          style: {
            marginTop: -16,
          },
        }}
        rowSelection={
          access.线索上报x选题计划x选题列表x收录线索 && {
            // 自定义选择项参考: https://ant.design/components/table-cn/#components-table-demo-row-selection-custom
            // 注释该行则默认不显示下拉选项
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            type: 'checkbox',
          }
        }
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          return (
            <Space size={24}>
              <span>
                已选 {selectedRowKeys.length} 项
                <a style={{ marginInlineStart: 8 }} onClick={onCleanSelected}>
                  取消选择
                </a>
              </span>
            </Space>
          );
        }}
        tableAlertOptionRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => {
          return (
            <Space size={16}>
              <ModalForm
                key={'adapt_modal_form'}
                layout={'horizontal'}
                title={
                  <>
                    <CheckCircleOutlined style={{ fontSize: '18px', color: '#87d068' }} />
                    <span
                      style={{
                        marginInlineStart: 10,
                      }}
                    >
                      批量收录
                    </span>
                  </>
                }
                trigger={<a>批量收录</a>}
                autoFocusFirstInput
                modalProps={{
                  destroyOnClose: true,
                  width: '500px',
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  const response = await adoptsSubmit({ ids: selectedRowKeys });
                  if (response.code === 0) {
                    message.success('批量收录成功');
                    onCleanSelected();
                    ref?.current?.reload();
                    return true;
                  } else {
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>是否确认批量收录</Typography.Paragraph>
              </ModalForm>
              <ModalForm
                key={'score_modal_form'}
                layout={'horizontal'}
                title={
                  <>
                    <CheckCircleOutlined style={{ fontSize: '18px', color: '#87d068' }} />
                    <span
                      style={{
                        marginInlineStart: 10,
                      }}
                    >
                      批量评分
                    </span>
                  </>
                }
                trigger={<a>批量评分</a>}
                autoFocusFirstInput
                modalProps={{
                  destroyOnClose: true,
                  width: '500px',
                }}
                submitTimeout={2000}
                onFinish={async (values) => {
                  const response = await scoresSubmit({ ids: selectedRowKeys, ...values });
                  if (response.code === 0) {
                    message.success('批量评分成功');
                    onCleanSelected();
                    ref?.current?.reload();
                    return true;
                  } else {
                    return true;
                  }
                }}
              >
                <Typography.Paragraph>是否确认批量评分</Typography.Paragraph>
                <ProFormDigit
                  width="md"
                  label="奖励"
                  name="score"
                  min={0.01}
                  max={100}
                  fieldProps={{ precision: 2 }}
                  rules={[{ required: true, message: '请输入奖励' }]}
                />
              </ModalForm>
            </Space>
          );
        }}
        // toolBarRender={() => [
        //   <ProFormCascader
        //     noStyle
        //     key={'organizationIds'}
        //     name="organizationIds"
        //     label="上报单位"
        //     placeholder={'上报单位'}
        //     fieldProps={{
        //       multiple: true,
        //       maxTagCount: 'responsive',
        //       options: articleOrganizations,
        //     }}
        //   />,
        // ]}
        toolBarRender={(action) => [
          access.线索上报x选题计划x选题列表x上报线索 && run === 1 && (
            <AddSubmit
              key="add_submit"
              topicPlan={plan}
              onRefurbish={() => {
                action?.reload();
              }}
            />
          ),
        ]}
        pagination={{
          showQuickJumper: true,
          showSizeChanger: true,
          defaultPageSize: 20,
        }}
      />
    </ProCard>
  );
};

export default TableTopicPlan;
